package com.oxygen.pt.controller;

import cn.hutool.core.bean.BeanUtil;
import com.deepoove.poi.XWPFTemplate;
import com.github.pagehelper.PageInfo;
import com.oxygen.pt.pojo.dto.ChamberInspectionMonthlySaveDTO;
import com.oxygen.pt.pojo.entity.ChamberInspectionMonthly;
import com.oxygen.pt.pojo.vo.ChamberInspectionMonthlyVO;
import com.oxygen.pt.pojo.vo.Result;
import com.oxygen.pt.service.ChamberInspectionMonthlyService;
import com.oxygen.pt.utils.InspectionRemarkConverter;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/chamber/monthly")
public class ChamberInspectionMonthlyController {

    @Resource
    private ChamberInspectionMonthlyService service;

    /* 新增 */
    @PostMapping
    public Result<Long> save(@Validated @RequestBody ChamberInspectionMonthlySaveDTO dto) {
        Long id = Long.valueOf(service.save(dto));
        return Result.success(id);
    }

    /* 删除 */
    @DeleteMapping("/{id}")
    public Result<Void> remove(@PathVariable Long id) {
        int rows = service.remove(id);
        return rows > 0 ? Result.success() : Result.error("删除失败");
    }

    /* 更新 */
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id,
                               @Validated @RequestBody ChamberInspectionMonthlySaveDTO dto) {
        // 1. 查询旧记录
        ChamberInspectionMonthly entity = service.findById(id);
        if (entity == null) {
            return Result.error("记录不存在");
        }
        // 2. 合并更新
        BeanUtil.copyProperties(dto, entity, "id");   // 忽略主键
        entity.setId(id);
        entity.setRemarksJson(InspectionRemarkConverter.buildRemarksJson(dto));
        int rows = service.modify(entity);
        return rows > 0 ? Result.success() : Result.error("更新失败");
    }

    /* 单条查询 */
    @GetMapping("/{id}")
    public Result<ChamberInspectionMonthlySaveDTO> detail(@PathVariable Long id) {
        ChamberInspectionMonthlySaveDTO dto = service.findDtoById(id);
        return dto != null ? Result.success(dto) : Result.error("记录不存在");
    }


    /* 分页查询 */
    @GetMapping("/page")
    public Result<PageInfo<ChamberInspectionMonthlyVO>> page(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam Long chamberId,
            @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
            @RequestParam(required = false)
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {

        PageInfo<ChamberInspectionMonthlyVO> pageInfo =
                service.page(pageNum, pageSize, chamberId, startTime, endTime);
        return Result.success(pageInfo);
    }

    @GetMapping("/export/word")
    public void exportWord(HttpServletResponse response,
                           @RequestParam Long chamberId,
                           @RequestParam Integer year) throws IOException {

        Map<String,Object> data = service.buildWordData(chamberId, year);

        // 模板路径
        try (InputStream is = this.getClass()
                .getResourceAsStream("/templates/monthly_template.docx");
             OutputStream os = response.getOutputStream()) {

            XWPFTemplate template = XWPFTemplate.compile(is).render(data);
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode("氧舱月检_" + year + ".docx", StandardCharsets.UTF_8));
            template.write(os);
            template.close();
        }
    }
}